import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTimerStore = defineStore('timer', () => {
    // 状态
    const totalSeconds = ref(0)
    const isRest = ref(false)
    const lastUpdate = ref(null)
    const currentDate = ref(new Date().toLocaleDateString()) // 使用ref包装

    // 日期检查方法修正
    function checkDateChange() {
        const today = new Date().toLocaleDateString()
        if (currentDate.value !== today) {
            totalSeconds.value = 0
            currentDate.value = today
            lastUpdate.value = null
        }
    }

    // Getters
    const formattedDuration = computed(() => {
        const hours = Math.floor(totalSeconds.value / 3600)
        const minutes = Math.floor((totalSeconds.value % 3600) / 60)
        const seconds = totalSeconds.value % 60
        return [hours, minutes, seconds]
            .map(v => v.toString().padStart(2, '0'))
            .join(':')
    })

    // Actions
    function checkDateChange() {
        const today = new Date().toISOString().split('T')[0]
        if (currentDate.value !== today) {
            totalSeconds.value = 0
            currentDate.value = today
        }
    }

    function startWork() {
        checkDateChange()
        isRest.value = false
        lastUpdate.value = Date.now()
    }

    function startRest() {
        isRest.value = true
        lastUpdate.value = Date.now()
    }

    function updateDuration() {
        if (!isRest.value && lastUpdate.value) {
            const now = Date.now()
            const seconds = Math.floor((now - lastUpdate.value) / 1000)
            totalSeconds.value += seconds
            lastUpdate.value = now
        }
    }

    return {
        totalSeconds,
        isRest,
        lastUpdate,
        currentDate,
        formattedDuration,
        startWork,
        startRest,
        updateDuration
    }
}, {
    persist: {
        key: 'work_timer',
        storage: localStorage,
        paths: ['totalSeconds', 'isRest', 'lastUpdate', 'currentDate'],
        serializer: {
            serialize: JSON.stringify,
            deserialize: JSON.parse
        }
    }
})
